package flc.ast.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.view.TextStickerView;

import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseEditVideoFragment;
import flc.ast.R;
import flc.ast.activity.VideoEditActivity;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.FragmentVideoTextBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link VideoTextFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class VideoTextFragment extends BaseEditVideoFragment<FragmentVideoTextBinding> {

    public static final int INDEX = Content.INDEX_TEXT;
    private InputMethodManager imm;
    private TextStickerView mTextStickerView;
    private List<MyColorBean> mColorBeanList;
    private ColorAdapter mColorAdapter;
    private int tmpPos;
    private int videoWidth;
    private int videoHeight;

    public static VideoTextFragment newInstance() {
        VideoTextFragment fragment = new VideoTextFragment();
        return fragment;
    }

    @Override
    public void onShow() {
        if (mColorAdapter != null) {
            mColorAdapter.getItem(tmpPos).setSelect(false);
            tmpPos = 0;
            mColorAdapter.getItem(tmpPos).setSelect(true);
            mColorAdapter.notifyDataSetChanged();
        }
        videoHeight = mVideoEditActivity.mVideoView.getHeight();
        videoWidth = mVideoEditActivity.mVideoView.getWidth();
        mTextStickerView.setVisibility(View.VISIBLE);
        // 将stickerView的宽高大小设置成videoView一样的大小
        mVideoEditActivity.mVideoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                RelativeLayout.LayoutParams stickerLayoutParams = (RelativeLayout.LayoutParams) mTextStickerView.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mTextStickerView.setLayoutParams(stickerLayoutParams);
            }
        });
        mVideoEditActivity.mode = VideoEditActivity.MODE_TEXT;
//        mVideoEditActivity.mVideoView.setVideoPath(mVideoEditActivity.getMainPath());

        mDataBinding.etPicTextContent.clearFocus();
        mTextStickerView.setTextColor(Color.parseColor("#000000"));
    }

    @Override
    public void backToMain() {
        mColorAdapter.getItem(tmpPos).setSelect(false);
        hideInput();
        mVideoEditActivity.mVideoView.setVideoPath(mVideoEditActivity.getMainPath());
        mVideoEditActivity.mVideoView.seekTo(1);
        mVideoEditActivity.mVideoView.start();
        mVideoEditActivity.mImageView.setImageResource(R.drawable.azant);
        mVideoEditActivity.mode = VideoEditActivity.MODE_NONE;
        mTextStickerView.setVisibility(View.GONE);
        mVideoEditActivity.showFunc();
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_video_text;
    }

    @Override
    protected void initView() {
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mTextStickerView = mVideoEditActivity.mTextStickerView;

        mColorBeanList = new ArrayList<>();
        tmpPos = 0;

        mDataBinding.tvPicTextConfirm.setOnClickListener(this);

        mDataBinding.rvPicText.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mColorAdapter = new ColorAdapter();
        mDataBinding.rvPicText.setAdapter(mColorAdapter);
        mColorAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvPicTextConfirm:
                KeyboardUtils.hideSoftInput(getActivity());
                if (TextUtils.isEmpty(mDataBinding.etPicTextContent.getText().toString())) {
                    ToastUtils.showShort(R.string.et_text_content_tips);
                    return;
                }
                mTextStickerView.setText(mDataBinding.etPicTextContent.getText().toString());
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mColorAdapter.getItem(tmpPos).setSelect(false);
        mColorAdapter.getItem(position).setSelect(true);
        tmpPos = position;
        mColorAdapter.notifyDataSetChanged();

        mTextStickerView.setTextColor(Color.parseColor(mColorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#000000", true));
        listColor.add(new MyColorBean("#FFFFFF", false));
        listColor.add(new MyColorBean("#E12D2D", false));
        listColor.add(new MyColorBean("#FFA8A8", false));
        listColor.add(new MyColorBean("#FFB652", false));
        listColor.add(new MyColorBean("#FFF62C", false));
        listColor.add(new MyColorBean("#79BA56", false));
        listColor.add(new MyColorBean("#35B9B0", false));
        listColor.add(new MyColorBean("#3F68BC", false));
        listColor.add(new MyColorBean("#9F45F1", false));
        listColor.add(new MyColorBean("#E85C90", false));
        listColor.add(new MyColorBean("#C0C0C0", false));
        listColor.add(new MyColorBean("#CA58C9", false));
        listColor.add(new MyColorBean("#8A72E1", false));
        listColor.add(new MyColorBean("#46D5AF", false));
        listColor.add(new MyColorBean("#5E8C4F", false));
        mColorAdapter.setList(listColor);
        onShow();
    }

    public void hideInput() {
        if (getActivity() != null && getActivity().getCurrentFocus() != null && isInputMethodShow()) {
            imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public boolean isInputMethodShow() {
        return imm.isActive();
    }

    public void applyTextVideo() {
        if (mVideoEditActivity.mVideoView.isPlaying()) {
            mVideoEditActivity.mVideoView.pause();
            mVideoEditActivity.mImageView.setImageResource(R.drawable.azant);
        }
        showDialog(getString(R.string.video_text_loading) + "0%");
        mTextStickerView.setShowHelpBox(false);
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mTextStickerView);
                imagePath = FileUtil.generateFilePath("/image", ".png");
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                epDraw.setRotate(0);
                String resultFile = FileUtil.generateFilePath(Content.app_tmp_video, ".mp4");
                EpVideo epVideo = new EpVideo(mVideoEditActivity.getMainPath());
                epVideo.addDraw(epDraw);
                EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissDialog();
                                ToastUtils.showShort(R.string.video_text_success);
                                mVideoEditActivity.changeMainPath(resultFile, true);
                                backToMain();
                            }
                        });
                    }

                    @Override
                    public void onFailure() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShort(R.string.video_text_fail);
                                FileUtils.delete(resultFile);
                                dismissDialog();
                            }
                        });
                    }

                    @Override
                    public void onProgress(float progress) {
                        showDialog(getString(R.string.video_text_loading) + (int) (progress * 100) + "%");
                    }
                });
            }
        });
    }

}